var app = getApp();
Page({
  data: {
    listData: [],
    scale: '11',
    controls: '40',
    latitude: '',
    longitude: '',
    markers: [],
    lightList: [],
    pdList: [],
    pdId: '',
    pdLightList: [],
    pdLightIdList: [],
    fakeScale: 11,
    hasSmall: false,
    canLook: false,
    keyword: '',
    inputInfo: '',
    searchResultList: [],
    isBad:false,
    lightId:'',
    toPdDetail:false,
    chooseStatus:false,
    isAdmin:true,
  },
  onLoad: function(options) {
    console.log(options)
    
    var userName = wx.getStorageSync("userName")
    if (!userName || userName == "" || userName == null) {
      wx.showModal({
        title: '提示',
        content: "用户未登录",
        confirmText: '去登录',
        showCancel: false,
        success: function() {
          wx.redirectTo({
            url: '../login/login',
          })
        }
      })
    } else {
      
      if(wx.getStorageSync("roleId") == 315 || true){
        this.setData({
          isAdmin:true,
        })
      }else{
      //   this.setData({
      //     treamId:wx.getStorageSync("treamId"),
      //   })
      //   wx.showLoading({
      //     title: '加载中',
      //  })   
      //   this.init(userName, options)
      }
    }
    this.getTeamList()
  },
  onReady: function() {
    // 页面渲染完成
    this.mapCtx = wx.createMapContext("map");
   
    if(this.data.isAdmin){
      setTimeout(()=>{this.movetoCenter()},300)
      
    }
  },
  onShow: function() {
    // 页面显示

  },
  onHide: function() {
    // 页面隐藏
  },
  onUnload: function() {
    // 页面关闭
  },
  onShareAppMessage: function() {

  },
  movetoCenter(){
    this.mapCtx.moveToLocation();
  },
  init(userName, options) {
    var that = this
    var params = {
      userName: wx.getStorageSync("userName"),
      pageNumber: 1,
      pageSize: 10000,
      filter: 1,
      deptId: wx.getStorageSync('deptId'),
      treamId: this.data.treamId,
      choosenTreamId: 1,
    }
    var encodingStr = app.ecbEncrypto(params)
    //获取路灯
    // wx.request({
    //   url: app.url + '/web/streetLamp/getList.htm',
    //   data: encodingStr,
    //   method: 'POST',
    //   success: function(res) {
    //     var decodingStr = app.ecbDecrypto(res.data);
    //     var rest = JSON.parse(decodingStr)
    //     console.log(rest)
    //     if (rest.isSuccess == 0) {
    //       var list = rest.result.content
    //       that.setData({
    //         lightList: list
    //       })
    //     }
    //   },
    //   complete: function() {
    //     wx.stopPullDownRefresh()
    //     wx.hideLoading()
    //   }
    // })
    //获取配电箱
    wx.request({
      url: app.url + '/web/distridutionBox/getList.htm',
      data: encodingStr,
      method: 'POST',
      success: function(res) {
        var decodingStr = app.ecbDecrypto(res.data);
        var rest = JSON.parse(decodingStr)
        console.log(rest)
        if (rest.isSuccess == 0) {
          var list = rest.result.content
          if (options.latitude) {
            wx.getLocation({
              type: 'wgs84', //返回可以用于wx.openLocation的经纬度
              success: (res) => {
                that.setData({
                  scale: 20,
                  longitude: options.longitude,
                  latitude: options.latitude
                })
              }
            });
          } else {
            if(list.length == 0){return}
            let longitude = list[0].lngLat.split(",")[0]
            let latitude = list[0].lngLat.split(",")[1]
            wx.getLocation({
              type: 'wgs84', //返回可以用于wx.openLocation的经纬度
              success: (res) => {
                that.setData({
                  scale: 11,
                  longitude: longitude,
                  latitude: latitude
                })
              }
            });
          }
          that.setData({
            pdList: list
          })
          that.setData({
            markers: that.getpdMarkers(),
          })

        }
      },
      complete: function() {
        wx.stopPullDownRefresh()
        wx.hideLoading()
      }
    })
  },
  inputgetKeyword(e) {
    this.setData({
      inputInfo: e.detail.value
    })
  },
  controltap(e) {
    this.moveToLocation()
  },
  getLightMarkers() {
    var market = [];
    for (let item of this.data.lightList) {
      var marker1;
      if (item.state != 1) {
        marker1 = this.createPdLightMarker(item);
      } else {
        marker1 = this.createMarker(item);
      }
      market.push(marker1)
    }

    for (let item of this.data.pdList) {
      let marker1 = this.createPdMarker(item);
      market.push(marker1)
    }
    return market;
  },
  getPdLightMarkers() {
    var market = [];
    for (let item of this.data.pdLightList) {
      let marker1 = this.createPdLightMarker(item);
      market.push(marker1)
    }
    return market;
  },
  getpdMarkers() {
    var market = [];
    for (let item of this.data.pdList) {
      let marker1 = this.createPdMarker(item);
      market.push(marker1)
    }
    if (this.data.pdLightList.length > 0) {
      for (let item of this.data.pdLightList) {
        let marker1 = this.createPdLightMarker(item);
        market.push(marker1)
      }
    }
    return market;
  },
  moveToLocation: function() {
    this.mapCtx.moveToLocation()

  },
  createMarker(point) {
    let arr = point.lngLat.split(",");
    let latitude = arr[1];
    let longitude = arr[0];
    let state = point.state || '无';
    let address = point.address || '无';
    let marker = {
      iconPath: point.state == 0 ? "../../images/light_01.png" : "../../images/light_02.png",
      // id: point.id + ',路灯,' + state + ',' + address,
      id:Number('222' + point.id),
      state: point.state,
      name: '路灯',
      title: point.address,
      latitude: latitude,
      longitude: longitude,
      exceptionReportId: point.exceptionReportId,
      zIndex: 1,
      label: {
        x: -24,
        y: -26,
        content: ''
      },
      width: 25,
      height: 25,
      anchor:{x: 1, y: 1}
    };
    return marker;
  },
  createPdLightMarker(point) {
    let arr = point.lngLat.split(",");
    let latitude = arr[1];
    let longitude = arr[0];
    let state = point.state || '无'
    let address = point.address || '无';
    
    let marker = {
      iconPath: point.state == 0 ? "../../images/light_03.png" : "../../images/light_02.png",
      // id: point.id + ',路灯,' + state + ',' + address,
      id:Number('222' + point.id),
      name: '路灯',
      title: point.placeName || '',
      details: {
        latitude: latitude,
        longitude: longitude,
      },
      zIndex: 5,
      callout: {
        padding: 0,
        content: point.address,
        borderRadius: 3,
        display:'ALWAYS',
        fontSize:"18rpx",
      },
      latitude: latitude,
      longitude: longitude,
      // label: {
      //   anchorX: -24,
      //   anchorY: y,
      //   padding: 2,
      //   content: point.address,
      //   borderRadius: 3,
      //   bgColor:"#fff",
      //   fontSize:"20rpx"
      // },
      width: 25,
      height: 25,
      anchor:{x: 1, y: 1}
    };
    return marker;
  },
  createPdMarker(point) {
    let arr = point.lngLat.split(",");
    let latitude = arr[1];
    let longitude = arr[0];
    let state = point.state || '无'
    let address = point.name || '无';
    let marker = {
      iconPath: this.data.pdId == point.id ? "../../images/pd_02.jpg":"../../images/pd_01.jpg",
      // id: point.id + ',配电箱,' + state + ',' + address,
      id: Number('111' + point.id),
      name: '配电箱',
      callout: {
        padding: 0,
        content: point.name,
        borderRadius: 3,
        display:'ALWAYS',
        fontSize:"18rpx",
      },
      latitude: latitude,
      longitude: longitude,
      label: {
        x: -24,
        y: -26,
        content: ''
      },
      width: 25,
      height: 35,
    };
    return marker;
  },
  markertap(e,b) {
    console.log(e)
    let name = String(e.markerId).substr(0,3) == '111'?'配电箱':'路灯';
    let markerId = e.markerId.toString().substr(3);
    let markerObj = name=='配电箱'?this.data.pdList.find(it=>(it.id == markerId)):this.data.pdLightList.find(it=>(it.id == markerId));
    console.log(markerObj);
    let state = markerObj.state;
    let address = name=='配电箱'?markerObj.name:markerObj.address;
    
    if (name == '路灯') {
      this.setData({
        canLook: true,
        keyword: address,
        isBad: state == 1,
        lightId:markerId,
        toPdDetail:false,
        lightName:address
      })
      return
    } else if (name == '配电箱') {
      // if (markerId == this.data.pdId) {
      //   this.setData({
      //     pdId:'',
      //     canLook: true,
      //     toPdDetail:true,
      //     isBad:false,
      //     pdName:address
      //   })

      // }
      this.setData({
        pdId: markerId == this.data.pdId?'':markerId,
        canLook: true,
        toPdDetail:true,
        isBad: false,
        pdName:address
      })
      //获取配电箱下路灯
      var userName = wx.getStorageSync("userName")
      var that = this
      var params = {
        userName: userName,
        pageNumber: 1,
        pageSize: 10000,
        filter: 1,
        distributionBoxid: markerId,
      }
      console.log(params);
      var encodingStr = app.ecbEncrypto(params)
      wx.request({
        url: app.url + '/web/streetLamp/getList.htm',
        data: encodingStr,
        method: 'POST',
        success: (res) => {
          var decodingStr = app.ecbDecrypto(res.data);
          var rest = JSON.parse(decodingStr)
          console.log(rest)
          if (rest.isSuccess == 0) {
            var list = rest.result.content
            var idList = [];
            rest.result.content.forEach(item => {
              idList.push(item.id)
            })
            const oldPdLightList = this.data.pdLightList;
            const isDelete = this.data.pdLightList.findIndex(item=>item.id == list[0].id) > -1;
            console.log(isDelete)
            if(isDelete && !this.data.pdId){
              const newList = this.data.pdLightList.filter(item=>{
                return !(list.findIndex(it=>(item.id == it.id)) > -1)
              })
              that.setData({
                pdLightList: newList,
              })
            }else if(isDelete && this.data.pdId){

            }else{
              that.setData({
                pdLightList: [...this.data.pdLightList,...list],
              })
            }
            wx.nextTick(()=>{
              let list = that.getpdMarkers()
              that.setData({
                    markers: list,
              })
            })
           
            
            // let list = that.getpdMarkers()
            // wx.getLocation({
            //   type: 'wgs84', //返回可以用于wx.openLocation的经纬度
            //   success: (res) => {
            //     // let list = that.data.fakeScale >= 13 ? that.getLightMarkers() : that.getpdMarkers();
            //     let list = that.getpdMarkers()
            //     that.setData({
            //       markers: list,
            //     })
            //   },fail: res => {
                
            //     console.log(res);
            //   }
            // });
          }
        },
        complete: function () {
          wx.stopPullDownRefresh()
          wx.hideLoading()
        }
      })
      return
    } else{
      this.setData({
        canLook: false,
      })
    }

  },
  regionchange(e) {
    let that = this;
    if (e.causedBy == 'scale') {
      this.mapCtx.getScale({
        success: (res) => {
          that.setData({
            fakeScale: res.scale,
          })

          if (res.scale >= 13) {
            if (that.data.hasSmall) {
              return
            } else {
              that.setData({
                hasSmall: true,
              })
            }
            // wx.getLocation({
            //   type: 'wgs84', //返回可以用于wx.openLocation的经纬度
            //   success: (res) => {
            //     that.setData({
            //       markers: that.getLightMarkers(),
            //     })
            //   }
            // });
          } else {
            if (!that.data.hasSmall) {
              return
            } else {
              that.setData({
                hasSmall: false,
              })
            }
            wx.getLocation({
              type: 'wgs84', //返回可以用于wx.openLocation的经纬度
              success: (res) => {
                that.setData({
                  markers: that.getpdMarkers(),
                })
              }
            });
          }
        },
        fail: (res) => {

        }
      });
    }
  },
  toLook() {
    wx.navigateTo({
      url: '../reportList/reportList?keyword=' + this.data.keyword,
    })
  },
  toDetail() {
    if(this.data.toPdDetail){
      wx.navigateTo({
        url: '/pages/pd/detail?id=' + this.data.pdId,
      })
    }else{
      wx.navigateTo({
        url: '/pages/light/detail?id=' + this.data.lightId,
      })
    }
    
  },
  toSearch() {
    var that = this;
    var userName = wx.getStorageSync("userName")
    var deptId = wx.getStorageSync("deptId")
    var treamId = wx.getStorageSync("treamId")
    var params = {
      pageNumber: 1,
      pageSize: 10000,
      address: this.data.inputInfo,
      userName: userName,
      deptId: deptId,
      // treamId: treamId != 0?treamId:'',
    }
    console.log(params)
    var encodingStr = app.ecbEncrypto(params)
    wx.request({
      url: app.url + '/web/streetLamp/getList.htm',
      data: encodingStr,
      method: 'POST',
      success: function(res) {
        var decodingStr = app.ecbDecrypto(res.data);
        var rest = JSON.parse(decodingStr)
        if (rest.isSuccess == 0) {
          var list = rest.result.content
          that.setData({
            searchResultList: list
          })
          // console.log(list)
        }
      },
      complete: function() {

      }
    })
    var params = {
      name: this.data.inputInfo,
      deptId: wx.getStorageSync('deptId'),
      // treamId: treamId != 0?treamId:'',
      userName: userName,
      pageNumber: 1,
      pageSize: 10000,
    }
    // console.log(params)
    var paramsCode = app.ecbEncrypto(params)
    wx.request({
      url: app.url + '/web/distridutionBox/getList.htm',
      data: paramsCode,
      method: 'POST',
      success: function (res) {
        var decodingStr = app.ecbDecrypto(res.data);
        var rest = JSON.parse(decodingStr)
        console.log(rest)
        if (rest.isSuccess == 0) {
          var list = rest.result.content
          that.setData({
            searchResultListPd: list
          })
          console.log(list)
        }
      },
      complete: function () {

      }
    })
  },
  moveLight(e) {
    var that = this;
    let obj = e.currentTarget.dataset.lnglat.split(",");
    console.log(obj)
    let latitude = obj[1];
    let longitude = obj[0];
    wx.getLocation({
      type: 'wgs84', //返回可以用于wx.openLocation的经纬度
      success: (res) => {
        that.setData({
          scale: 20,
          longitude: longitude,
          latitude: latitude,
          // markers: that.getLightMarkers(),
        })
      }
    });
    console.log(e.currentTarget.dataset.movetype)
    if(e.currentTarget.dataset.movetype == 2){
      var userName = wx.getStorageSync("userName")
      var that = this
      var params = {
        userName: userName,
        pageNumber: 1,
        pageSize: 10000,
        filter: 1,
        distributionBoxid: e.currentTarget.dataset.pdid,
      }
      var encodingStr = app.ecbEncrypto(params)
      wx.request({
        url: app.url + '/web/streetLamp/getList.htm',
        data: encodingStr,
        method: 'POST',
        success: function (res) {
          var decodingStr = app.ecbDecrypto(res.data);
          var rest = JSON.parse(decodingStr)
          console.log(rest)
          if (rest.isSuccess == 0) {
            var list = rest.result.content
            var idList = [];
            rest.result.content.forEach(item => {
              idList.push(item.id)
            })
            that.setData({
              pdLightList: list,
            })
            wx.getLocation({
              type: 'wgs84', //返回可以用于wx.openLocation的经纬度
              success: (res) => {
                // let list = that.data.fakeScale >= 13 ? that.getLightMarkers() : that.getpdMarkers();
                let list = that.getpdMarkers()
                that.setData({
                  markers: list,
                })
              },fail: res => {
                
                console.log(res);
              }
            });
          }
        },
        complete: function () {
          wx.stopPullDownRefresh()
          wx.hideLoading()
        }
      })
    }
    this.setData({
      inputInfo: e.currentTarget.dataset.address,
      searchResultList: [],
      searchResultListPd: [],
    })
    console.log(obj)
  },
  getTeamList(){
    var that = this;
    var params = {
      pageNumber: 1,
      pageSize: 10000,
      deptid: 4,
      type: 1,
    }
    var paramsCode = app.ecbEncrypto(params)
    wx.request({
      url: app.url + '/web/sysTream/getList.htm',
      data: paramsCode,
      method: 'POST',
      success: function (res) {
        var decodingStr = app.ecbDecrypto(res.data);
        var rest = JSON.parse(decodingStr)
        console.log(rest)
        if (rest.isSuccess == 0) {
          var list = rest.result.content
          that.setData({
            teamList: list
          })
        }
      },
      complete: function () {

      }
    })
  },
  checkboxChange:function(e){
    this.setData({
      treamId:e.detail.value.toString(),
      markers: [],
    })
    console.log(e.detail.value)
    if(e.detail.value.length > 0){
      this.init("",{})
    }
  },
  changechooseStatus(e){
    this.setData({
      chooseStatus:e.currentTarget.dataset.status
    })
  },
  toBao(){
    wx.navigateTo({
      url: '/pages/innerReport/innerReport?scene=' + this.data.lightId,
    })
  }
});